<template>
  <i-biz-view-shell
    v-if="isLoaded"
    :context="viewData.context"
    :params="viewData.params"
    :viewId="viewData.viewConfig.id"
    :key="viewData.viewConfig.codeName"
    :state="{ srfnav: viewData.srfnav }"
  ></i-biz-view-shell>
</template>

<script setup lang="ts">
import { IBizContext } from "@ibiz-template/core";
import { parseRouteViewData, currentRoute } from "@/utils";
import { IRouteViewData } from "@/interface";
import { onReady, onUnload } from "@dcloudio/uni-app";
import { ref, toRaw } from "vue";

const isLoaded = ref(false);

const viewData = ref<IRouteViewData>({});

/**
 * 初始化视图数据
 */
const initViewData = async () => {
  try {
    const route = currentRoute();
    const _viewData = await parseRouteViewData(route);
    viewData.value = {
      ..._viewData,
      context: IBizContext.create(_viewData.context),
    };
    isLoaded.value = true;
  } catch (error) {
    uni.redirectTo({
      url: "/pages/404",
    });
  }
};

/**
 * 销毁上下文
 */
const destroyContext = () => {
  if (viewData.value.context) {
    const { context } = toRaw(viewData.value);
    if (context) context.destroy();
  }
};

/**
 * 渲染完成
 */
onReady(() => {
  initViewData();
});

/**
 * 页面卸载
 */
onUnload(() => {
  destroyContext();
});
</script>

<style lang="scss" scoped>
//
</style>
